<template>
  <NavigationBar>
    <div class="manage">
      <Row>
        <i-col span="16">
          <i-input
            v-model="name"
            size="large"
            @on-change="setName"
            maxlength="40"
            show-word-limit
            placeholder="文章标题"
          />
        </i-col>
        <i-col span="4">
          <Button size="large" @click="save" type="dashed">保存草稿</Button>
        </i-col>
        <i-col span="4">
          <Button size="large" @click="publish" type="info">发布文章</Button>
        </i-col>
      </Row>
    </div>
    <!--编辑发布信息-->
    <div class="editInfo" style="text-align: center">
      <Modal
        :closable="false"
        v-model="isShow"
        :mask-closable="false"
        title="发布文章"
      >
        <Divider>文章简要描述</Divider>
        <i-input
          v-model="describe"
          maxlength="100"
          :autosize="{ minRows: 2, maxRows: 5 }"
          show-word-limit
          type="textarea"
          placeholder="文章简要描述"
        />
        <Divider>文章分类</Divider>
        <i-select :disabled="disabled" v-model="sort" filterable>
          <Option v-for="item in sortList" :value="item.id" :key="item.id">{{
            item.name
          }}</Option>
        </i-select>
        <Divider>文章标签</Divider>
        <i-select :disabled="disabled" v-model="tags" filterable multiple>
          <Option v-for="item in tagsList" :value="item.id" :key="item.id">{{
            item.name
          }}</Option>
        </i-select>
        <Divider>是否允许评论</Divider>
        <RadioGroup v-model="isComment">
          <Radio label="允许"></Radio>
          <Radio label="不允许"></Radio>
        </RadioGroup>

        <div slot="footer" style="text-align: center">
          <Row>
            <i-col span="12">
              <Button type="error" @click="cancel" size="large">取消</Button>
            </i-col>
            <i-col span="12">
              <Button type="info" @click="ok" size="large">发布</Button>
            </i-col>
          </Row>
        </div>
      </Modal>
    </div>
    <!--编辑发布信息-->
    <div class="write" v-show="!isShow">
      <!--        defaultOpen="preview" :subfield="false" :toolbarsFlag="false"-->
      <mavon-editor
        :ishljs="true"
        @save="save"
        ref="md"
        @imgAdd="$imgAdd"
        @change="change"
        :toolbars="markdownOption"
        v-model="contentMd"
      ></mavon-editor>
    </div>
  </NavigationBar>
</template>

<script>
import NavigationBar from "@/components/common/NavigationBar";
import {
  allCategories,
  allTags,
  insertArticle,
  insertImage,
  insertDraft,
  updateDraft,
  updateArticle,
  judgeDraft,
} from "@/network/write";
import { getArticleById } from "@/network/articleDetail";

export default {
  name: "Write",
  components: {
    NavigationBar,
  },
  data() {
    return {
      //文章标题
      name: "",
      isShow: false,
      //文章Id
      articleId: 0,
      articleInfo: {},
      //草稿箱id
      draftId: 0,
      //文章描述
      describe: "",
      sort: "",
      sortList: [],
      tagsList: [],
      tags: [],
      isComment: "允许",
      disabled: false,
      //markdown样式
      markdownOption: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      contentHtml: "",
      contentMd: "",
    };
  },
  mounted() {
    //获取从文章管理那里跳转过来
    let articleId = this.$route.params.articleId;
    if (articleId !== undefined) {
      this.articleId = articleId;
      this.getArticleById(articleId);
    }
    //获取全部的分类和标签信息
    this.allCategories();
    this.allTags();
    this.contentMd = this.$store.state.contentMd;
    this.name = this.$store.state.title;
    this.draftId = this.$store.state.draftId;
    if (this.$route.params.title !== undefined) {
      this.draftId = this.$route.params.id;
      this.articleId = this.$route.params.articleId;
      this.name = this.$route.params.title;
      this.contentMd = this.$route.params.contentMd;
    }
  },
  methods: {
    publish() {
      if (this.name === "") {
        this.$Message.error("标题不能为空！");
        return;
      }
      if (this.contentMd === "") {
        this.$Message.error("文章内容不能为空！");
        return;
      }
      this.isShow = true;
    },
    //发布文章
    ok() {
      if (this.describe === "") {
        this.$Message.error({
          background: true,
          content: "文章简要描述不能为空！",
        });
        return;
      }
      if (this.sort === "") {
        this.$Message.error({
          background: true,
          content: "文章分类不能为空！",
        });
        return;
      }
      if (this.tags.length === 0) {
        this.$Message.error({
          background: true,
          content: "文章标签不能为空！",
        });
        return;
      }
      let allowComment = true;
      if (this.isComment !== "允许") {
        allowComment = false;
      }
      //如果文章id 为0 则插入新的文章 否则更新文章
      if (this.articleId === 0) {
        insertArticle(
          this.name,
          this.contentHtml,
          this.contentMd,
          Number(this.sort),
          this.tags,
          this.describe,
          allowComment
        )
          .then((res) => {
            if (res.code === 2000) {
              this.$Message.success({
                background: true,
                content: "发布成功！",
              });
              this.articleId = res.data.articleId;
              this.isShow = false;
            }
          })
          .catch(() => {
            this.$Message.error({
              background: true,
              content: "发布失败！",
            });
          });
      } else {
        updateArticle(
          this.articleId,
          this.name,
          this.contentHtml,
          this.contentMd,
          this.describe,
          allowComment
        ).then((res) => {
          if (res.code === 2000) {
            this.$Message.success({
              background: true,
              content: "更新文章成功！",
            });
            this.isShow = false;
            return;
          }
          this.$Message.error({
            background: true,
            content: "更新文章失败！",
          });
        });
      }
    },
    //输入框数据改变是触发
    setName() {
      if (this.name !== 0) {
        this.$store.commit("setTitle", this.name);
      }
    },
    cancel() {
      this.describe = "";
      this.tags = [];
      this.sort = "";
      this.isComment = "允许";
      this.isShow = false;
    },
    //数据改变
    change(value, render) {
      this.contentMd = value;
      this.contentHtml = render;
      this.$store.commit("setContentMd", value);
    },
    allCategories() {
      allCategories().then((res) => {
        this.sortList = res.data.categoriesList;
      });
    },
    allTags() {
      allTags().then((res) => {
        this.tagsList = res.data.tagsList;
      });
    },
    //插入图片
    $imgAdd(pos, $file) {
      console.log(pos);
      let formdata = new FormData();
      formdata.append("file", $file);
      insertImage(formdata)
        .then((res) => {
          if (res.code === 2000) {
            this.$refs.md.$img2Url(pos, res.data.url);
          }
        })
        .catch(() => {
          this.$Message.error("上传图片失败！");
        });
    },
    //保存草稿
    save() {
      if (this.name === "") {
        this.$Message.error("标题不能为空！");
        return;
      }
      if (this.contentMd === "") {
        this.$Message.error("文章内容不能为空！");
        return;
      }
      this.$store.commit("setArticleId", this.articleId);
      //草稿箱id为空则进行插入操作
      if (this.draftId === 0) {
        insertDraft(this.articleId, this.name, this.contentHtml, this.contentMd)
          .then((res) => {
            this.draftId = res.data.draftId;
            this.$store.commit("setDraftId", res.data.draftId);
            this.$Message.success("保存成功！");
          })
          .catch(() => {});
      } else {
        //存在草稿箱Id则进行更新操作
        updateDraft(
          this.draftId,
          this.articleId,
          this.name,
          this.contentHtml,
          this.contentMd
        ).then((res) => {
          if (res.code === 2000) {
            this.$Message.success("更新成功！");
          }
        });
      }
    },
    //获取文章详细信息
    getArticleById(articleId) {
      getArticleById(articleId).then((res) => {
        let article = res.data.article;
        this.articleInfo = article;
        this.contentMd = article.contentMd;
        this.name = article.title;
        this.sort = article.categoryId;
        let tags = [];
        for (let tag of article.tags) {
          tags.push(tag.id);
        }
        this.tags = tags;
        this.describe = article.description;
        if (article.allowComment) {
          this.isComment = "允许";
        } else {
          this.isComment = "不允许";
        }
        //修改文章不允许更改标签和分类
        this.disabled = true;
        //判断文章是否有草稿
        judgeDraft(articleId).then((res) => {
          if (res.code === 2000) {
            this.draftId = res.data.draftId;
          }
        });
      });
    },
  },
};
</script>

<style scoped>
.manage {
  margin-top: 30px;
  margin-bottom: 35px;
  text-align: center;
}
</style>
